package main

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

type Person struct {
	Id   string `uri:"id" binding:"required"`
	Name string `uri:"name" binding:"required"`
}

func main() {

	r := gin.Default()

	demo := r.Group("/demo")
	{
		demo.GET("/:id/:action", goodsDetail)
		demo.GET("/ps/:name/:id", personDetail)

		demo.POST("/post", formPost)
		demo.GET("/welcome", welcome)
	}
	r.Run(":8888")
}

func welcome(c *gin.Context) {
	firstName := c.DefaultQuery("firstname", "bobby")
	lastName := c.DefaultQuery("lastname", "imooc")
	c.JSON(http.StatusOK, gin.H{
		"first_name": firstName,
		"last_name":  lastName,
	})
}

func formPost(c *gin.Context) {
	nickName := c.PostForm("nickName")
	message := c.DefaultPostForm("message", "this is test message")
	c.JSON(http.StatusOK, gin.H{
		"nickName": nickName,
		"message":  message,
	})
}

func personDetail(c *gin.Context) {

	var p Person
	if err := c.ShouldBindUri(&p); err != nil {
		c.Status(404)
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"name": p.Name,
		"id":   p.Id,
	})
}

func goodsDetail(c *gin.Context) {

	id := c.Param("id")
	action := c.Param("action")

	c.JSON(http.StatusOK, gin.H{
		"id":     id,
		"action": action,
	})
}
